package hz.mobileproject.pda.ui.activity.work;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.activity.CaptureActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cn.droidlover.xdroidmvp.mvp.XActivity;
import cn.droidlover.xdroidmvp.net.NetError;
import hz.mobileproject.pda.R;
import hz.mobileproject.pda.broadcast.HandleBroadcast;
import hz.mobileproject.pda.broadcast.IShowBarcodeStr;
import hz.mobileproject.pda.db.DBManager;
import hz.mobileproject.pda.entity.ImpBuWeiBean;
import hz.mobileproject.pda.entity.request.Request_Imp_Call;
import hz.mobileproject.pda.entity.request.Request_Imp_End;
import hz.mobileproject.pda.entity.request.Request_Imp_List;
import hz.mobileproject.pda.entity.request.Request_Imp_start;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.ImpBackContent;
import hz.mobileproject.pda.entity.response.Response_Imp_start;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.presenter.PImpBuWei;
import hz.mobileproject.pda.ui.adapter.ImpBuWeiAdapter;
import hz.mobileproject.pda.ui.view.LoadingDialog;
import hz.mobileproject.pda.utils.CommonUtil;

public class ImpBuWeiActivity extends XActivity<PImpBuWei> implements IShowBarcodeStr {

    private static final String TAG = "ImpBuWeiActivity";
    private HandleBroadcast mHandleBroadcast;
    private SoundPool mSoundPool;
    private int mSoundId;
    private static final int SCAN_PLOCE_REQUEST_CODE = 0x111;
    private static final int SCAN_THING_REQUEST_CODE = 0x222;

    private SPUtils spUtils;
    private SPUtils spUtils_cusNumber;
    private String cusNumber;
    private String policeName;
    private LoadingDialog mLoadingDialog;
    private boolean firstSaoMiao = true;

    //民警编号
    private String police_code;
    private Gson gson;
    private Response_loadPoliceInfo loadPoliceInfo;
    private String departmentId;
    private String departmentName;
    private String policeId;
    private String mNowTime;
    private TextView tv_shidian;
    private TextView tv_getNum;
    private int shidian = 0;
    private int totalNum;
    /** 开始中 主表ID*/
    private String check_id;
    private String parts_total;  //清点数量
    private ImpBuWeiAdapter mImpBuWeiAdapter;

    /** 第二个接口*/
    private List<ImpBuWeiBean> impBuWeiBeanList;

    /** 第三个接口,清点 */
    private String abnormalType = "0";
    private String abnormalRemark = "";
    //清点的接口
    private List<Request_Imp_Call> mRequest_imp_callList;
    private DBManager mDbManager;
    private RecyclerView recyclerView;
    private TextView mTv_reson;

    private String end_key = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected void onResume() {
        super.onResume();
        try {
            //测试过程中先注释掉
//            handleBroadcast.sendMyBroadcast();
        } catch (Exception e) {
            e.printStackTrace();
        }

//        List<Request_Imp_End> request_imp_ends = mDbManager.queryImpEnd();
//        for(int i = 0; i < request_imp_ends.size(); i++) {
//            Request_Imp_End request_imp_end = request_imp_ends.get(i);
//            getP().setData(gson.toJson(request_imp_end),6);
//        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //查询所有清点 时候未上传的数据
        //后面查询数据库中是否有未清点的人,然后上传
        List<Request_Imp_Call> request_imp_calls_ErrorList = mDbManager.queryRequest_Imp_CallingList();
        if(request_imp_calls_ErrorList.size() != 0) {
            getP().setData(gson.toJson(request_imp_calls_ErrorList), 5);   //重新请求清点的处理数据
        }


        if (mHandleBroadcast != null) {
            mHandleBroadcast.overBroadcastReceiver(this);
        }

        List<Request_Imp_End> request_imp_ends = mDbManager.queryImpEnd();
        for(int i = 0; i < request_imp_ends.size(); i++) {
            Request_Imp_End request_imp_end = request_imp_ends.get(i);
            getP().setData(gson.toJson(request_imp_end),6);
        }


    }

    /**
     * 打开扫描
     */
    private void openScan(int requestCode) {
        mLoadingDialog = new LoadingDialog(this);
        if (Constance.isNeiMeng) {  //如果是演示版本则打开相机扫描
            //打开二维码扫描界面
            if (CommonUtil.isCameraCanUse()) {
                Intent intent = new Intent(this, CaptureActivity.class);
                startActivityForResult(intent, requestCode);
            } else {
                Toast.makeText(this, "请打开此应用的摄像头权限！", Toast.LENGTH_SHORT).show();
            }
        } else {
            mHandleBroadcast = new HandleBroadcast(this, this);
            mSoundPool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
            mSoundId = mSoundPool.load("/etc/Scan_new.ogg", 1);
            mLoadingDialog.setMessage("请扫描民警二维码").show();
        }
    }



    @Override
    public void updateText(String msg) {
        mSoundPool.play(mSoundId, 1, 1, 0, 0, 1);
        LogUtils.e(TAG,msg);
        boolean status = msg.contains("P");
        if(status && firstSaoMiao ) {
            firstSaoMiao = !firstSaoMiao;
            //是民警
            police_code = msg.substring(1);
            LogUtils.e(TAG,"获取民警信息" + police_code);
            //查询民警信息
            Request_loadPoliceInfo callroll_loadPoliceInfo = new Request_loadPoliceInfo();
            callroll_loadPoliceInfo.setCusNumber(spUtils.getString("cusnumber"));
            callroll_loadPoliceInfo.setPoliceCode(police_code);  //3304281  一监区
            //请求网络的入口
            getP().setData(gson.toJson(callroll_loadPoliceInfo), 1);



        }else {
            if(impBuWeiBeanList == null) {
                ToastUtils.showShort("未查询到数据");
                return;
            }
            //是重点检查部位 (扫描重点检查部位)
                for (int i = 0; i < impBuWeiBeanList.size(); i++) {
                    ImpBuWeiBean impBuWeiBean = impBuWeiBeanList.get(i);
                    String partsCode = impBuWeiBean.parts_code;
                    String partsName = impBuWeiBean.parts_name;
                    String time = TimeUtils.getNowString();
                    //扫描得到的是重点部位的编号
                    if (msg.equals(impBuWeiBean.parts_code)) {
                        //扫描的重点部位编号和 服务器返回的集合中的某一条数据相等
                        Request_Imp_Call request_imp_call = new Request_Imp_Call();
                        //cusNumber,check_id,policeId,policeName,partsId,partsName,time,abnormalType,abnormalType
                        request_imp_call.setCusNumber(cusNumber);
                        request_imp_call.setCheckId(check_id);
                        request_imp_call.setPoliceId(policeId);
                        request_imp_call.setPoliceName(policeName);
                        request_imp_call.setPartsCode(partsCode);
                        request_imp_call.setPartsName(partsName);
                        request_imp_call.setTime(time);
                        request_imp_call.setAbnormalType(abnormalType);
                        request_imp_call.setAbnormalRemark(abnormalRemark);
                        request_imp_call.setStatus("1");   //默认扫描到的状态为正常
                        mRequest_imp_callList = new ArrayList<>();
                        mRequest_imp_callList.add(request_imp_call);
                        getP().setData(gson.toJson(mRequest_imp_callList), 4);

                        //TODO mAdapter.remove()操作
                        mImpBuWeiAdapter.remove(impBuWeiBean);
                        impBuWeiBeanList.remove(impBuWeiBean);
                    }
                }
            }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(SCAN_PLOCE_REQUEST_CODE == requestCode && CaptureActivity.RESULT_CODE_QR_SCAN == resultCode){
            //是民警
            police_code = data.getStringExtra(CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN);
            if(police_code.indexOf("P")==0){
                police_code = police_code.replace("P","");
            }
            LogUtils.e(TAG,"获取民警信息" + police_code);
            //查询民警信息
            Request_loadPoliceInfo callroll_loadPoliceInfo = new Request_loadPoliceInfo();
            callroll_loadPoliceInfo.setCusNumber(spUtils.getString("cusnumber"));
            callroll_loadPoliceInfo.setPoliceCode(police_code);  //3304281  一监区
            //请求网络的入口
            getP().setData(gson.toJson(callroll_loadPoliceInfo), 1);
        }

        if(SCAN_THING_REQUEST_CODE == requestCode && CaptureActivity.RESULT_CODE_QR_SCAN == resultCode){
            if(impBuWeiBeanList == null) {
                ToastUtils.showShort("未查询到数据");
                return;
            }
            //是重点检查部位 (扫描重点检查部位)
            for (int i = 0; i < impBuWeiBeanList.size(); i++) {
                ImpBuWeiBean impBuWeiBean = impBuWeiBeanList.get(i);
                String partsCode = impBuWeiBean.parts_code;
                String partsName = impBuWeiBean.parts_name;
                String time = TimeUtils.getNowString();
                //扫描得到的是重点部位的编号
                if (impBuWeiBean.parts_code.equals(data.getStringExtra(CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN))) {
                    //扫描的重点部位编号和 服务器返回的集合中的某一条数据相等
                    Request_Imp_Call request_imp_call = new Request_Imp_Call();
                    //cusNumber,check_id,policeId,policeName,partsId,partsName,time,abnormalType,abnormalType
                    request_imp_call.setCusNumber(cusNumber);
                    request_imp_call.setCheckId(check_id);
                    request_imp_call.setPoliceId(policeId);
                    request_imp_call.setPoliceName(policeName);
                    request_imp_call.setPartsCode(partsCode);
                    request_imp_call.setPartsName(partsName);
                    request_imp_call.setTime(time);
                    request_imp_call.setAbnormalType(abnormalType);
                    request_imp_call.setAbnormalRemark(abnormalRemark);
                    request_imp_call.setStatus("1");   //默认扫描到的状态为正常
                    mRequest_imp_callList = new ArrayList<>();
                    mRequest_imp_callList.add(request_imp_call);
                    getP().setData(gson.toJson(mRequest_imp_callList), 4);

                    //TODO mAdapter.remove()操作
                    mImpBuWeiAdapter.remove(impBuWeiBean);
                    impBuWeiBeanList.remove(impBuWeiBean);
                }
            }
        }
    }

    @Override
    public void onWidgetClick(View view) {

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        tv_shidian = (TextView) findViewById(R.id.tv_shidian);
        tv_getNum = (TextView) findViewById(R.id.tv_getnum);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(ImpBuWeiActivity.this));
        gson = new Gson();
        spUtils = SPUtils.getInstance("app_login");
        openScan(SCAN_PLOCE_REQUEST_CODE);   // 初始化广播

//        //开始获取配置
//        spUtils = SPUtils.getInstance("Callroll_loadCnf");
//        spUtils_cusNumber = SPUtils.getInstance("app_login");
//
//        cusNumber = spUtils_cusNumber.getString("cusnumber");
//        departmentId =

        mDbManager = DBManager.getInstance(getApplicationContext());

        Button end_button = (Button) findViewById(R.id.to_end);
        mTv_reson = (TextView) findViewById(R.id.tv_reason);
        Button bt_submit = (Button) findViewById(R.id.bt_submit);
        end_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getP().setData("a",7);   //显示单选对话框
            }
        });

        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if("".equals(end_key)) {
                    ToastUtils.showLong("还未选择部门检查结束原因,无法提交");
                    return;
                }
                String end_time = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
                String endModes = "1";
                String reson = end_key;
                Request_Imp_End request_imp_end = new Request_Imp_End();
                request_imp_end.setCusNumber(cusNumber);
                request_imp_end.setPoliceId(policeId);
                request_imp_end.setCheckId(check_id);
                request_imp_end.setEndTime(end_time);
                request_imp_end.setEndModes(endModes);
                request_imp_end.setHandEndReason(reson);
                getP().setData(gson.toJson(request_imp_end),6);    //
            }
        });

        Button btn_scan = (Button) findViewById(R.id.btn_scan);
        btn_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openScan(SCAN_THING_REQUEST_CODE);
            }
        });
        if(Constance.isNeiMeng){
            btn_scan.setVisibility(View.VISIBLE);
        }else{
            btn_scan.setVisibility(View.GONE);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_imp_buwei;
    }

    @Override
    public PImpBuWei newP() {
        return new PImpBuWei();
    }

    //P处理逻辑后,返回处理后的 data中的String
    public void setView(String data_json, int type) {
        switch (type) {
            case 1 : {

                loadPoliceInfo = gson.fromJson(data_json, Response_loadPoliceInfo.class);

                departmentId = loadPoliceInfo.getDepartment_id() + "";
                departmentName = loadPoliceInfo.getDepartment_name();
                policeId = loadPoliceInfo.getPolice_id();
                policeName = loadPoliceInfo.getPolice_name();
                mNowTime = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
                cusNumber = loadPoliceInfo.getCus_number() + "";
                startDianMing();

                //用于未检查重点部位 接口的请求
                spUtils.put("cusNumber_imp",cusNumber);
                spUtils.put("departmentId_imp",departmentId);
            }
            break;
            case 2: {  //开始
                Response_Imp_start response_imp_start = gson.fromJson(data_json,Response_Imp_start.class);
                LogUtils.e(TAG,"清点数量" + response_imp_start.parts_total);
                check_id = response_imp_start.check_id;
                parts_total = response_imp_start.parts_total;

                getImpBuWeiList();

                spUtils.put("check_id_imp",check_id);
            }
            break;
            case 3 : {    //查询重点部位检查列表
                impBuWeiBeanList = gson.fromJson(data_json,new TypeToken<List<ImpBuWeiBean>>(){}.getType());
//                LogUtils.e(TAG,"查询重点部位检查列表数量" + impBuWeiBeanList.size());
                if(impBuWeiBeanList == null) {
                    ToastUtils.showLong("未查询到数据");
                    firstSaoMiao = !firstSaoMiao;
                    return;
                }
                tv_getNum.setText(impBuWeiBeanList.size() + "");
                totalNum = impBuWeiBeanList.size();

                mImpBuWeiAdapter = new ImpBuWeiAdapter(impBuWeiBeanList);
                recyclerView.setAdapter(mImpBuWeiAdapter);
                mLoadingDialog.dismiss();
                mImpBuWeiAdapter.setImpItemClickListener(new ImpBuWeiAdapter.OnImpItemClickListener() {
                    @Override
                    public void OnImpItemClick(View view, int position) {
                        //条目点击回调
//                        ToastUtils.showLong(position + "");
                    }
                });
            }
            break;
            case 4 : {   //清点
                //请点返回  如果剩余个数为0  则自动调结束接口
                shidian++;
                tv_shidian.setText(shidian + "");
                tv_shidian.setTextColor(Color.RED);
                totalNum--;
                if(totalNum == 0) {
                    String end_time = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
                    String endModes = "1";
                    String reson = "";
                    Request_Imp_End request_imp_end = new Request_Imp_End();
                    request_imp_end.setCusNumber(cusNumber);
                    request_imp_end.setPoliceId(policeId);
                    request_imp_end.setCheckId(check_id);
                    request_imp_end.setEndTime(end_time);
                    request_imp_end.setEndModes(endModes);
                    request_imp_end.setHandEndReason(reson);
                    getP().setData(gson.toJson(request_imp_end),6);    //结束
                }

            }
            break;
            case 5 : {   //数据库中的 清点
                mDbManager.deleteErrorCalling();
            }
            break;
            case 6 :{    //结束
                ToastUtils.showLong("重点部位检查成功");
                end_key = "";
                finish();
            }
            break;
            case 7 : {
                LogUtils.e(TAG,data_json);
                List<ImpBackContent> ImpBackContentList = gson.fromJson(data_json,new TypeToken<List<ImpBackContent>>(){}.getType());
                List<String> valueList = new ArrayList<>();
                List<String> keyList = new ArrayList<>();
                for(int i= 0; i < ImpBackContentList.size();i++) {
                    valueList.add(ImpBackContentList.get(i).value);
                    keyList.add(ImpBackContentList.get(i).key);
                }
                final String resons[] = valueList.toArray(new String[0]);
                final String keys[] = keyList.toArray(new String[0]);
                final AlertDialog.Builder builder = new AlertDialog.Builder(ImpBuWeiActivity.this);
                    mAlertDialog =builder.setIcon(R.mipmap.icon)
                            .setTitle("请选择退出原因")
                            .setSingleChoiceItems(resons, -1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //8月31日修改为  点击提交按钮才请求end接口
                                    mTv_reson.setText(resons[which]);
                                    end_key = keys[which];

//                                    Toast.makeText(ImpBuWeiActivity.this, keys[which], Toast.LENGTH_SHORT).show();
                                    //调用end的接口

                                    mAlertDialog.dismiss();
                                }
                            }).create();
                    mAlertDialog.show();

            }
            break;
        }
    }

   private AlertDialog mAlertDialog;
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            //点击返回键, 则请求网络获取对话框中展示的String
//
//           return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    //开始点名
    private void startDianMing() {
        Request_Imp_start request_imp_start = new Request_Imp_start(cusNumber,departmentId,departmentName,mNowTime,policeId);
        getP().setData(gson.toJson(request_imp_start),2);
    }
    //查询重点部位检查列表
    private void getImpBuWeiList() {
        Request_Imp_List request_imp_list = new Request_Imp_List(cusNumber,departmentId,check_id);
        getP().setData(gson.toJson(request_imp_list),3);
    }

    public void Error(NetError error, String requestData, int type) {
        switch (type) {
            case 4 :{
                //清点失败
                List<Request_Imp_Call> request_imp_callList_error = gson.fromJson(requestData,new TypeToken<List<Request_Imp_Call>>(){}.getType());
                for (int i = 0; i < request_imp_callList_error.size();i++) {   //清点失败,循环集合
                    Request_Imp_Call request_imp_call = request_imp_callList_error.get(i);
                    mDbManager.insertImpBuWeiCalling(request_imp_call);
                }
            }
            break;
            case 6 : {
                //结束失败
                Request_Imp_End request_imp_end_error = gson.fromJson(requestData,Request_Imp_End.class);
                //数据库中插入结束失败的数据
                mDbManager.insertImpEnd(request_imp_end_error);
            }
            break;
        }
    }

}
